<template>
  <view class="page-wrapper">
    <nav-bar title="测试"></nav-bar>

    <view class="page-main">
      <scroll-view>
        <view class="page-container">
          <br />
          <button @click="down_2">本页面的请求</button>

          <br />
          <button @click="down_4('1735021375509')">请求4-jpg</button>
          <button @click="down_4('1735265041139')">请求4-jpg</button>
          <button @click="down_4('1735265050313')">请求4-jpg</button>
          <button @click="down_4('1735200826667')">请求4-svg</button>
          <button @click="down_4('1735021697460')">请求4-png</button>
          <button @click="down_4('1735263771487')">请求4-png(头像)</button>
          <button @click="down_4('1735265061794')">请求4-mp4</button>

          <button @click="down_4('1735200821425')">请求4-gif</button>
          <button @click="down_4('1735007133856')">请求4-mp3</button>
          <button @click="down_4('1735200833040')">请求4-txt</button>
          <button @click="down_4('1735200803457')">请求4-xlsx</button>
          <button @click="down_4('1735200812087')">请求4-rar</button>

          <br />
          <button @click="down_7">请求7-删除文件</button>

          <br />
          <button @click="down_5">请求5-预览图片</button>
        </view>

        <AudioPlayer ref="audioPlayer" />
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import AudioPlayer from '@/pages/only/audioPlayer.vue'; // 根据实际路径引入子组件
const audioPlayer = ref(null);

function getBaseUrl() {
  const baseUrl = uni.getStorageSync('serverUrl');
  if (!baseUrl) {
    uni.showToast({
      title: '未配置服务器地址',
      icon: 'none',
      duration: 2000,
    });
    return null;
  }
  return baseUrl;
}

const info = reactive({
  // videoSrc: '',
});

// 直接下载
// {
//     "tempFilePath": "_doc/uniapp_temp_1735199916785/download/1735020432304_IMG_20240830_164507.jpg",
//     "statusCode": 200,
//     "errMsg": "downloadFile:ok"
// }

const down_4 = (fileno) => {
  const pre_url = getBaseUrl();
  uni.downloadFile({
    url:
      pre_url +
      '/eis.gridfileload?service=appuService&method=download&flag=upload&appuseq=' +
      fileno,
    success: (downloadRes) => {
      console.log('downloadRes', downloadRes);
      if (downloadRes.statusCode === 200) {
        const tempFilePath = downloadRes.tempFilePath;

        // _doc/uniapp_temp_1735207098102/download/1735020754132_Screenshot_2023-02-13-15-11-23-998_plus.H5CA74F17.png
        const fileType = tempFilePath.split('.').pop().toLowerCase();
        // const fileName = tempFilePath.split('/').pop();
        console.log('fileType', fileType);

        if (['jpg', 'jpeg', 'png', 'gif'].includes(fileType)) {
          console.log('是图片类型喽');
          uni.previewImage({
            urls: [tempFilePath],
            success: () => {
              console.log('图片预览成功');
            },
            fail: (error) => {
              console.error('图片预览失败:', error);
              // 这里可以添加重定向到登录页面的逻辑
            },
          });
        } else if (['mp3', 'wav', 'ogg'].includes(fileType)) {
          console.log('是音频喽');
          // audioPlayer
          // const innerAudioContext = uni.createInnerAudioContext();
          // innerAudioContext.src = tempFilePath; // 设置音频文件路径
          // innerAudioContext.play(); // 播放音频

          // innerAudioContext.onEnded(() => {
          //   console.log('音频播放结束');
          // });

          // innerAudioContext.onError((error) => {
          //   console.error('音频播放错误:', error);
          // });

          audioPlayer.value.open(tempFilePath);
        } else if (['mp4', 'avi', 'mov', 'wmv'].includes(fileType)) {
          console.log('是视频文件喽');
          uni.navigateTo({
            url: `/pages/only/videoPlayer?src=${encodeURIComponent(
              tempFilePath
            )}`, // 传递视频源
          });
        } else {
          console.log('非三界文件');
          uni.showToast({
            // title: '暂不支持该类型',
            title: '只能预览移动端上传的文件',
            icon: 'none',
          });
        }
      } else {
        console.error('文件下载失败:', downloadRes);
      }
    },
    fail: (error) => {
      console.error('下载请求失败:', error);
    },
  });
};

const deleteTempFile = (filePath) => {
  return new Promise((resolve, reject) => {
    // 先获取保存的文件列表
    uni.getSavedFileList({
      success: (res) => {
        const fileList = res.fileList;
        console.log(267, fileList);
        const targetFile = fileList.find((file) =>
          file.filePath.includes(filePath)
        );
        console.log(277, targetFile);

        if (targetFile) {
          uni.removeSavedFile({
            filePath: targetFile.filePath,
            success: () => {
              console.log('文件删除成功');
              resolve(true);
            },
            fail: (err) => {
              console.error('删除文件失败:', err);
              reject(err);
            },
          });
        } else {
          console.error('未找到目标文件');
          reject(new Error('文件不存在'));
        }
      },
      fail: (err) => {
        console.error('获取文件列表失败:', err);
        reject(err);
      },
    });
  });
};

/*
[
    {
        "filePath": "_doc/uniapp_save/17351994372500.jpg",
        "createTime": 1735199437000,
        "size": 113673
    },
]
*/

const tempFilePath = '_doc/uniapp_save/17351999439260.jpg';
const down_7 = async () => {
  try {
    await deleteTempFile(tempFilePath);
  } catch (error) {
    console.error('操作失败:', error);
    uni.showToast({
      title: '删除文件失败',
      icon: 'none',
    });
  }
};

const down_5 = (item) => {
  uni.previewImage({
    urls: [tempFilePath],
  });
  console.log('打开了');
};
</script>

<style lang="scss" scoped></style>
